package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.RecommendUser;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //根据toUserId查询推荐的用户数据，只查询score最高的一条
    public RecommendUser queryWithMaxScore(Long toUserId) {
        //1、构建Criteria对象，设置查询条件
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //2、构建Query对象，根据score排序，获取第一条
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("score")))       //指定排序
                .skip(0)
                .limit(1);//指定分页，从0开始，每页查询1条
        //3、调用mongoTemplate查询
        return mongoTemplate.findOne(query,RecommendUser.class);
    }

    //查询推荐用户分页列表
    public List<RecommendUser> queryRecommendUserList(Long toUserId, Integer page,
                                                      Integer pagesize) {
        //1、构建Criteria对象，设置查询条件
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //2、构建Query对象，根据score排序，设置分页参数
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("score")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        //3、查询数据列表
        return mongoTemplate.find(query,RecommendUser.class);
    }

    //查询两个用户之间的推荐数据
    public RecommendUser queryByUserId(Long userId, Long toUserId) {
        Criteria criteria = Criteria.where("toUserId").is(toUserId)
                .and("userId").is(userId);
        Query query = Query.query(criteria);
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        //判断是否存在，设置默认的缘分值
        if(recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(userId);
            recommendUser.setToUserId(toUserId);
            recommendUser.setScore(95d);
        }
        return recommendUser;
    }
}
